package com.bdqn.ch05.controller;

import com.bdqn.ch05.entity.User;
import com.bdqn.ch05.service.UserService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

//@Controller  @ResponseBody
//@RestController
@Controller
public class UserController {

    @Resource
    UserService userService;

    //@RequestMapping(value = "/getuser")
    @GetMapping(value = "/getuser")
    public Object getUser(@RequestParam(required = false, value = "id") String id) {
        System.out.println("id:" + id);
        User user = new User();
        user.setUsrId(1L);
        user.setUsrName("zhangsan");
        return user;
    }

    //restfull 风格url
    //http://localhost:8080/crm/user/100
    @GetMapping(value = "/user/{id}")
    public User user(@PathVariable("id") Long usrId) {
        //User user = userService.getUser(usrId);
        System.out.println("id:" + usrId);
        User user = new User();
        user.setUsrId(usrId);
        user.setUsrName("zhangsan");
        return user;
    }

/*    @GetMapping(value = "/userlist/{id}")
    public Object getUserList(@PathVariable("id") Long usrId) {
        System.out.println("usrId:" + usrId);
        return userService.selectListBiz();
    }*/

    @GetMapping(value = "/userlist")
    public String getUserList(Model model, HttpSession session) {
        List<User> userList = userService.selectListBiz();
        model.addAttribute("userList", userList);
        return "list";
    }

    @RequestMapping("/dologin")
    public String dologin(String uname, String upwd, Model model, HttpSession session) {
        User user = userService.selectByUnameBiz(uname);
        if (user == null) {
            model.addAttribute("msg", "用户名不存在");
            return "redirect:error1";
        } else {
            if (user.getUsrPassword().equals(upwd)) {
                session.setAttribute("user", user);
                return "redirect:userlist";
            } else {
                model.addAttribute("msg", "密码不正确");
                return "error";
            }
        }
    }

    @RequestMapping("/error1")
    public String error1() {
        System.out.println("error1................");
        return "error";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/main")
    public String main() {
        System.out.println("main............");
        return "redirect:userlist";
    }

}
